<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;

//全局自定义不建议多，影响性能
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //允许应用程序在非生产环境中加载Laravel IDE Helper
        if ($this->app->environment() !== 'production') {
            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
        }
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('checkIds', function ($attribute, $value, $parameters, $validator) {
            return $this->checkIDs($value);
        });
        Validator::extend('isPositiveInteger', function ($attribute, $value, $parameters, $validator) {
            return $this->isPositiveInteger($value);
        });
    }

    protected function checkIDs($value)
    {
        $value = is_array($value) ? $value : explode(',', $value);

        foreach ($value as $id) {
            if (!$this->isPositiveInteger($id)) {
                return false;
            }
        }
        return true;
    }

    protected function isPositiveInteger($value, $rule = '', $data = '', $field = '')
    {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        } else {
            return false;
        }
    }

    //电话校验
    protected function isMobile($value)
    {
        // $rule='^1(3|4|5|7|8)[0-9]\d{8}$^';
        // $rule='^(\d{3,4}-)\d{7,8}$|1(3|4|5|7|8)[0-9]\d{8}$^';
        $rule = '^0\d{2,3}-\d{7,8}$|1(3|4|5|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
}
